#!/usr/bin/env node

const http = require('http'),
      fs = require('fs'),
      qs = require('querystring'),
      log = console.log;
let uploadHtml = `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>upload file</title>
</head>
<body>
  <form method="post" enctype="multipart/form-data" action="http://192.168.133.144:3000/">
    <label>upload file:</label>
    <input type="file" name="file">
    <input type="submit" value="upload">
  </form>
</body>
</html>
`;
let okHtml = `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>ok file</title>
</head>
<body>
  <div>ok</div>
</body>
</html>
`;
let errHtml = `
<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <title>err file</title>
</head>
<body>
  <div>err</div>
</body>
</html>
`;
function err(req,res){
  res.statusCode = 404;
  res.end(errHtml);
}
function getFileName(data){
  let msg = data.split('\r\n');
  msg = msg[1].split(';');
  msg = msg[2].split('=');
  msg = msg[1];
  msg = msg.slice(1,msg.length-1);
  return msg;
}
function getFileContent(data){
  let msg = data.split('\r\n');
  msg = msg.slice(4,msg.length-2);
  msg = msg.join('\r\n');
  console.log(msg);
  return msg;
}

http.createServer((req,res) => {
  log(`${req.url} ${req.method} HTTP/${req.httpVersion}`);
  log(req.headers);
  log('');
  if(req.url == '/'){
    if(req.method === 'GET'){ 
      res.end(uploadHtml);
    }else if(req.method === 'POST'){
      let data = '';
      req.setEncoding = 'binary';
      req.on('data',chunk => {
        data += chunk;
      });
      req.on('end',() => {
        log(data);
        log(data.split('\r\n'));
        log('req body byte length:', Buffer.byteLength(data));
        const filename = getFileName(data);
        const filecontent = getFileContent(data);
        fs.writeFileSync(filename,filecontent,{'encoding':'utf8'});
        res.end(okHtml);
      })
    }else{
      err(req,res);
    }
  }else{
    err(req,res);
  }
}).listen(3000)
